package com.wntms.config.filter;

import com.wntms.auser.service.impl.PrincipalUsername;
import com.wntms.auser.utils.JwtUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

//访问一次只经过一次过滤器
@Component
public class LoginFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");

        //判断有没有token
        if(token == null || token.equals("")) {
            //没有token，放行
            filterChain.doFilter(request, response);
            return;
        }

        //有token但是是错误的
        if(!JwtUtils.verify(token)) {
            //校验失败
            throw new RuntimeException("无效的token");
        }

        //token是有的，而且验证成功了，放行
        //告诉security框架，不要再认证了
        //有认证，但是还要查看有没有权限
        //解析token，可以获取用户名或者id
        //通过用户名查询数据库(多表查询)

        String account = JwtUtils.resolverToken(token).getClaim("account").asString();
        PrincipalUsername principalUsername = new PrincipalUsername(account);
        Authentication authentication = new UsernamePasswordAuthenticationToken(principalUsername.getName(), null, null);
        SecurityContextHolder.getContext().setAuthentication(authentication);

        filterChain.doFilter(request, response);

    }
}
